package com.linking.web.common;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Maps;
import java.util.concurrent.ConcurrentMap;

/**
 * Id生成工具类
 *
 * @author yaoweixin
 * @date 2018/10/9
 */
public class IdUtils {

  private final static ConcurrentMap<String, Snowflake> WORKER_MAPS = Maps
      .newConcurrentMap();

  /**
   * 生成ID生成器
   * @param workerId    worker Id
   * @param dataId      dataCenter Id
   * @return  format
   */
  public static Snowflake genIdWorker(int workerId, int dataId) {
    String key = String.format("key:%d:%d", dataId, workerId);
    if (!WORKER_MAPS.containsKey(key)) {
      synchronized (WORKER_MAPS) {
        if (!WORKER_MAPS.containsKey(key)) {
          WORKER_MAPS.put(key, IdUtil.createSnowflake(workerId, dataId));
        }
      }
    }
    return WORKER_MAPS.get(key);
  }
}
